import axios from 'axios'
import { message } from 'antd'

import { getToken } from '../utils/user-token'

const instance = axios.create({
  timeout: 10 * 1000,
})

//! request 请求拦截器:统一带上token
instance.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer ${getToken()}` //JWT固定格式
    return config
  },
  error => Promise.reject(error)
)

// response 响应拦截器：统一处理 errno 和 msg
instance.interceptors.response.use(res => {
  const resData = (res.data || {}) as ResType

  const { errno, data, msg } = resData

  if (errno !== 0) {
    // 错误提示
    if (msg) {
      message.error('ajax' + msg)
    }
    throw new Error('ajax' + msg)
  }

  return data as any
})

//  TypeScript 中的类型定义，用于描述响应数据的结构
export type ResType = {
  errno: number
  data?: ResDataType
  msg?: string
}

export type ResDataType = {
  [key: string]: any
}

export default instance
